import { constantRouters, asyncRouters } from '@/router/router.config'

function hasMenu(userMenus, route) {
  var name = route.name
  if (name) {
    var tempData = userMenus.get(name)
    if (tempData) {
      return { success: true, name: tempData.title, icon: tempData.icon }
    } else {
      return { success: false, name: null }
    }
  } else {
    return { success: true, name: null }
  }
}
function generaMenu(routers, userMenus) {
  var menus = []
  routers.forEach(route => {
    const tmp = { ...route }
    var validateRes = hasMenu(userMenus, tmp)
    if (validateRes.success) {
      if (tmp.children) {
        tmp.children = generaMenu(tmp.children, userMenus)
      }
      if (validateRes.name) {
        tmp.meta.title = validateRes.name
        tmp.meta.icon = validateRes.icon
      }
      menus.push(tmp)
    }
  })
  return menus
}

const permission = {
  state: {
    routers: [],
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouters.concat(routers)
    }
  },
  actions: {
    GenerateRoutes(context, data) {
      return new Promise(resolve => {
        let accessedRouters = []
        var permissionMenus = context.getters.permission.permissionMenus
        accessedRouters = generaMenu(asyncRouters, permissionMenus)
        // 真实环境中,请将下边一行删除
        // accessedRouters = asyncRouters
        context.commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission
